import uuidWrapper from "~utils/uuid";
import {getQuery} from "~utils/common";
import {stringifyHighlighsToViewstate} from "~manager/viewstateManager";
import {highlight} from "~api/highlightText/highlight";
import { store } from "~storage/store";
// import {highlight} from "~contents/api/highlightText/highlight";
// import {highlight, highlightByText} from "~contents/api/highlightText/";
const create = async (color, selection = window.getSelection()) => {
  const selectionString = selection.toString();
  if (!selectionString) return;

  let container = selection.getRangeAt(0).commonAncestorContainer;

  // Sometimes the element will only be text. Get the parent in that case
  // TODO: Is this really necessary?
  while (!container.innerHTML) {
    container = container.parentNode;
  }
  let contextText;
  // if (selectionString.indexOf(selection.focusNode.data) !== -1) { // 这说明所选中的文本已经跨了多个节点，此时一般不需要context了
  // if (selection.focusNode.data.indexOf(selectionString) === -1) { // 这说明所选中的文本已经跨了多个节点，此时一般不需要context了
  if (!selection.anchorNode.data) { // 如果开始选中的不是文本则跳过
    console.warn("anchor node data is null or undefined.");
    return;
  }
  const url = location.hostname + location.pathname;
  const highlightWithViewstate = await buildHighlightBlock(selection, container, url, location.href, color.color, color.textColor, "");
  highlight(highlightWithViewstate.string, highlightWithViewstate.container, selection,
    highlightWithViewstate.color, highlightWithViewstate.textColor,
    highlightWithViewstate.uuid, highlightWithViewstate.viewstate, highlightWithViewstate.ver);
  // const highlightWithViewstate = await buildHighlightBlock(selection, container, url, location.href, color.color, color.textColor, "");
  // highlight(highlightWithViewstate.string, highlightWithViewstate.container, selection,
  //   highlightWithViewstate.color, highlightWithViewstate.textColor,
  //   highlightWithViewstate.uuid, highlightWithViewstate.viewstate, highlightWithViewstate.ver);
  //
  // // await createShortcut(location.href);
  await store(url, highlightWithViewstate.viewstate);
}

const buildHighlightBlock = async (selection, container, url, href, color, textColor, comments) => {
  const text = selection.toString().replace(/\s+/ugm, '').trim();
  const highlight = {
    uuid: uuidWrapper(),
    container: getQuery(container),
    anchorNode: getQuery(selection.anchorNode),
    focusNode: getQuery(selection.focusNode),
    anchorOffset: selection.anchorOffset,
    focusOffset: selection.focusOffset,
    string: text,
    color,
    textColor,
    href,
    ver: "4.0.0",
    comments, // JM: comments must be the last one if in array (not here)
  }
  highlight.viewstate = stringifyHighlighsToViewstate(highlight);

  // Return the index of the new highlight:
  return highlight;
}

export default create;
